//
// Created by Zeppyrz on 2025/11/6.
//

#include "Tools.h"

#ifdef _WIN32
#  include <io.h>
#else
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <dirent.h>
#endif

namespace ZeDisk {

std::string Tools::GetDirectory(std::string path) {
  std::string data = "";
#ifdef _WIN32
  // 存储文件信息
  _finddata_t file;
  std::string dirpath = path + "/*.*";
  // 目录上下文
  intptr_t dir = _findfirst(dirpath.c_str(), &file);
  if (dir < 0) return data;

  do {
    if (file.attrib & _A_SUBDIR) continue; // 暂时不处理子目录
    char buf[1024] = {0};
    snprintf(buf, sizeof(buf), "%s,%u;", file.name, file.size);
    data += buf;
  } while (_findnext(dir, &file) == 0);
#else
  struct dirent *entry = 0;
  struct stat stat_buf;
  DIR *dir = opendir(path.c_str());
  if (dir == nullptr) return data;
  // 获取当前工作目录
  char cwd[1024] = {0};
  getcwd(cwd, sizeof(cwd));

  chdir(path.c_str()); // 改变工作目录
  char buf[1024] = {0};
  while ((entry = readdir(dir)) != nullptr) {
    lstat(entry->d_name, &stat_buf);
    if (S_ISDIR(stat_buf.st_mode)) continue; // 暂时不处理目录
    snprintf(buf, sizeof(buf), "%s,%ld;", entry->d_name, stat_buf.st_size);
    data += buf;
  }
  chdir(cwd); // 回到原来工作目录
#endif

  // 去除结尾分号
  if (!data.empty()) data.pop_back();

  return data;
}

}  // namespace ZeDisk
